package top.jacktgq.hsp.nio.buffer_channel;

import java.nio.ByteBuffer;

/**
 * @Author CandyWall
 * @Date 2020/11/11--13:45
 * @Description 只读的ByteBuffer：java.nio.HeapByteBufferR
 */
public class ReadOnlyBufferDemo {
    public static void main(String[] args) {
        //创建一个Buffer
        ByteBuffer buffer = ByteBuffer.allocate(64);
        for (int i = 0; i < 64; i++) {
            buffer.put((byte) i);
        }

        //读取
        buffer.flip();

        //得到一个只读的Buffer
        ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
        System.out.println(readOnlyBuffer.getClass());

        //可以进行读取，但是不能继续往里面添加数据了
        while (readOnlyBuffer.hasRemaining()) {
            System.out.println(readOnlyBuffer.get());
        }
        //如果往里面添加数据，会报java.nio.ReadOnlyBufferException异常
        //readOnlyBuffer.put((byte) 100);
    }
}
